package com.lsfb.testgamedemo.Service;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.MainThread;
import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Toast;

import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;
import com.lsfb.testgamedemo.App;
import com.lsfb.testgamedemo.LoginBean;
import com.lsfb.testgamedemo.Utils.AsynHttp;
import com.lsfb.testgamedemo.Utils.CommonValue;
import com.lsfb.testgamedemo.Utils.LittleUtils;
import com.lsfb.testgamedemo.Utils.NetCallBack;
import com.lsfb.testgamedemo.Utils.SPUtils;
import com.lsfb.testgamedemo.Utils.URLString;
import com.lsfbandroid.helloplugin.R;

import org.xutils.common.util.MD5;
import org.xutils.x;

import java.util.List;

import static android.R.attr.mode;
import static cn.jpush.android.d.f;
import static com.lsfb.testgamedemo.Utils.LittleUtils.SplitMsg;
import static com.lsfb.testgamedemo.Utils.LittleUtils.VeryPwd;
import static com.lsfb.testgamedemo.Utils.LittleUtils.partMsg2Order;


/**
 * Created by Administrator on 2017/2/16 0016.
 */

public class MainService extends AccessibilityService {

    private String TAG = "Nonsense";

    /**
     * 主线程
     */
    private MainThread mainThread;

    /**
     * 是否开始主线程
     */
    private boolean StartThread = false;

    /**
     * 当前的命令编号
     */
    private int OrderNum = -1;

    /**
     * 当前的命令数据
     */
    private String OrderData = "";

    /**
     * 保存当前的窗口
     */
    private String saveWindows = "";

    /**
     * 上一次进入的窗口
     */
    private String lastWindows = "";

    /**
     * 验证密码
     */
    private String RecivePwd = "333";

    /**
     * 标记是否进入循环刷房
     */
    private Boolean reset = false;

    /**
     * 储存上下文(线程中存储)
     */
    private Context mContext;


    /**
     * 是否已经点击了
     */
    private boolean IsClicked = false;


    /**
     * 点击几号麦（默认点击1号）
     */
    private String ClickNum = "1";
    /**
     * 输入的内容（例如，需要报麦的id）
     */
    private String InputData = "123";

    /**
     * 每次执行的休眠时间
     */
    private long TimeSleep = 200l;

    private int time = 0;

    /**
     * 是否轮训
     */
    private boolean startcheck = true;

    //识别的文字保存
    private String Room = "房间";
    private String EnterRoom = "进入我的房间";
    private String ExitRoom = "退出房间";
    private String NotifyRoomName = "修改房间名";
    private String LookRoom = "房间加锁";
    private String unLookRoom = "房间解锁";
    private String CloseChat = "关闭公屏";
    private String Gping = "公屏";
    private String OpenChat = "打开公屏";
    private String Exit = "退出";
    private String BanTalk = "禁麦";
    private String unBanTalk = "解除禁麦";
    private String Tman = "踢出房间";
    private String BaoMan = "设为旁听";
    private String Baoshu = "封闭此座位";
    private String ShangMai = "抱用户上麦";
    private String Jiefeng = "解封此座位";


    //特殊控件保存
    private String TextViewName = "android.widget.TextView";
    private String LinLayout = "android.widget.LinearLayout";
    private String List = "android.widget.ListView";
    private String ViewPagerName = "android.support.v4.view.ViewPager";
    private String HorizontalScrollView = "android.widget.HorizontalScrollView";


    //类名保存
    private String page1 = "com.yy.huanju.MainActivity";
    private String page_room = "com.yy.huanju.chatroom.ChatroomActivity";
    private String page_room_exit_menu = "com.yy.huanju.widget.dialog.d";
    private String page_room_serach_dialog = "com.yy.huanju.widget.dialog.b";
    private String page_room_exit_menu_exitdialog = "android.app.AlertDialog";
    private String page_rename_room = "com.yy.huanju.chatroom.internal.ChatRoomModifyNameActivity";
    private String page_lock_room = "com.yy.huanju.chatroom.internal.ChatRoomLockActivity";
    private String Progressdialg = "android.app.ProgressDialog";
    private String Baosheishangmai = "com.yy.huanju.chatroom.YGroupMemberActivity";

    //ID保存
    private String ExitBtnId = "com.yy.huanju:id/topbar_right_child_layout";
    private String ExitDialgoRightBtn = "android:id/button1";
    private String ExitDialgoleftBtn = "android:id/button2";
    private String Edittext_rename = "com.yy.huanju:id/room_name";
    private String Btn_PostRename = "com.yy.huanju:id/btn_modify";
    private String edit_RoomPass = "com.yy.huanju:id/room_pass";
    private String Btn_LoockRoom = "com.yy.huanju:id/btn_lock";
    private String Grid_chatroom = "com.yy.huanju:id/chatroom_gridview";
    private String Btn_SearchUser = "com.yy.huanju:id/layout_search"; //搜索按钮
    private String Edit_SearchUser = "com.yy.huanju:id/tv_alert_message"; //ID编辑框
    private String Btn_BaoUser = "com.yy.huanju:id/btn_positive"; //抱她上麦
    private String Btn_saveLaba = "com.yy.huanju:id/btn_topic_save"; //保存喇叭
    private String edit_laba = "com.yy.huanju:id/edit_text_topic"; //喇叭文字
    private String btn_edit_laba = "com.yy.huanju:id/layout_display_topic"; //编辑喇叭
    private String btn_enter_top = "com.yy.huanju:id/topbar_center_child_layout"; //进入在线列表
    private String btn_kicout = "com.yy.huanju:id/btn_kickout"; //列表图标踢

    /**
     * 命令列表
     */
    private String[] OrderArr = {"开始", "房名", "锁房", "暂停", "解锁", "清屏", "开屏", "关屏", "禁", "解禁", "踢", "旁听", "抱树", "封", "解封", "喇叭", "抱踢", "速度"};


    private Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            switch (msg.what) {
                case 1:
                    //改名的handler请求
                    break;
                case 2:
                    NotificationManager manager = (NotificationManager) MainService.this.getSystemService(Context.NOTIFICATION_SERVICE);
                    PendingIntent pendingintent = PendingIntent.getActivity(MainService.this, 0,
                            new Intent(MainService.this, App.class), 0);
                    Notification.Builder builder = new Notification.Builder(MainService.this);//新建Notification.Builder对象
                    builder.setContentTitle("Hello助手");//设置标题
                    builder.setContentText("账号已在别处登录或到期");//设置内容
                    builder.setSmallIcon(R.mipmap.ic_launcher);//设置图片
                    builder.setContentIntent(pendingintent);//执行intent
                    Notification notification = builder.getNotification();//将builder对象转换为普通的notification
                    manager.notify(2, notification);//运行notification
                    break;
                case 3:
                    NotificationManager manager1 = (NotificationManager) MainService.this.getSystemService(Context.NOTIFICATION_SERVICE);
                    PendingIntent pendingintent1 = PendingIntent.getActivity(MainService.this, 0,
                            new Intent(MainService.this, App.class), 0);
                    Notification.Builder builder1 = new Notification.Builder(MainService.this);//新建Notification.Builder对象
                    builder1.setContentTitle("Hello助手");//设置标题
                    builder1.setContentText("网络异常，请重启助手");//设置内容
                    builder1.setSmallIcon(R.mipmap.ic_launcher);//设置图片
                    builder1.setContentIntent(pendingintent1);//执行intent
                    Notification notification1 = builder1.getNotification();//将builder对象转换为普通的notification
                    manager1.notify(3, notification1);//运行notification
                    break;
            }
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        PendingIntent pendingintent = PendingIntent.getActivity(this, 0,
                new Intent(this, App.class), 0);
        Notification.Builder builder = new Notification.Builder(this);//新建Notification.Builder对象
        builder.setContentTitle("Hello助手");//设置标题
        builder.setContentText("正在运行");//设置内容
        builder.setSmallIcon(R.mipmap.ic_launcher);//设置图片
        builder.setContentIntent(pendingintent);//执行intent
        Notification notification = builder.getNotification();//将builder对象转换为普通的notification
        startForeground(1, notification);//让 MyService 变成一个前台服务，并在系统状态栏中显示出来。
        manager.notify(1, notification);//运行notification
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "开启新服务");
        flags = START_FLAG_REDELIVERY; //提高优先级
        return super.onStartCommand(intent, flags, startId);

    }

    @Override
    protected void onServiceConnected() {
        Log.e(TAG, "监听服务连接");
        AccessibilityServiceInfo info = new AccessibilityServiceInfo();
        info.eventTypes = AccessibilityEvent.TYPES_ALL_MASK;
        info.feedbackType = AccessibilityServiceInfo.FEEDBACK_SPOKEN;
        info.notificationTimeout = 200;
        setServiceInfo(info);
        info.packageNames = new String[]{"com.yy.huanju"};
        setServiceInfo(info);
        super.onServiceConnected();
        GetSpeed();
        Log.e(TAG, "主线程开启");
        mainThread = new MainThread(this);
        mainThread.start();
        StartThread = true;
        errorthread.start();
        startcheck = true;
        CheckThread.start();

    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        int eventype = event.getEventType();
        switch (eventype) {
            case AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED: //监听通知栏的消息
                GetPwd();
                List<CharSequence> texts = event.getText();
                if (!texts.isEmpty()) {
                    for (CharSequence text : texts) {
                        String content = text.toString();
                        Log.e(TAG, "****接收的文本内容****:" + content);
                        if (SplitMsg(content) != null)//对消息体进行分离
                        {
                            Log.e(TAG, "****接收的消息内容****:" + SplitMsg(content));
                            if (VeryPwd(SplitMsg(content), RecivePwd)) //验证密码
                            {
                                Log.e(TAG, "****密码验证正确****");
                                String[] order = partMsg2Order(OrderArr, content);
                                if (order != null) //如果返回有命令或者有命令数据就执行下一步.
                                {
                                    OrderNum = Integer.parseInt(order[0]);
                                    OrderData = order[1];
                                    Log.e(TAG, "***接收到的命令序号是:***" + order[0] + "****" + "接收的命令数据是:" + order[1]);
                                    reset = false;
                                    if (OrderNum == 0) {
                                        TimeSleep = timedelay;
                                    } else {
                                        TimeSleep = 600l;
                                    }
                                    if (OrderNum == 3) {
                                        StartErrorTheard = false;
                                    } else {
                                        StartErrorTheard = true;
                                    }
                                }
                            } else {
                                Log.e(TAG, "****密码验证错误****");
                            }
                        }
                    }
                }
                break;

            case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
                Log.e(TAG, "*******变化的窗口名称*******" + event.getClassName().toString());
                lastWindows = saveWindows;
                DoOrder = true;
                saveWindows = event.getClassName().toString();
                break;
            case AccessibilityEvent.TYPE_VIEW_CLICKED:
                break;

        }
    }

    @Override
    public void onInterrupt() {
        Log.e(TAG, "服务停止");
        StartThread = false;
        StartErrorTheard = false;
        Log.e(TAG, "主线程停止");
    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "服务停止");
        Log.e(TAG, "主线程停止");
        stopForeground(true);
        StartThread = false;
        StartErrorTheard = false;
        super.onDestroy();
    }

    public void RestData() {
        reset = false;
        OrderNum = 0;
        TimeSleep = 200;
        IsClicked = false;
    }

    private boolean DoOrder = true;


    public class MainThread extends Thread {

        public MainThread(Context context) {
            mContext = context;
        }

        @Override
        public void run() {
            super.run();
            while (true) {
                while (StartThread && CommonValue.CanUse && DoOrder) {
                    DoOrder = false;
                    switch (OrderNum) {
                        case 0: //执行自动刷房
                            Log.e(TAG, "开始执行");
                            if (saveWindows != lastWindows) {
                                Log.e(TAG, "savewindows:" + saveWindows + "---lastwindows:" + lastWindows);
                                LoopMain();
                            }
                            break;
                        case 1: //改房名
                            if (OrderData.isEmpty()) {
                                Log.e(TAG, "额外数据为空");
                                RestData();
                            } else {
                                ReNameRoom();
                            }
                            break;
                        case 2: //锁房操作（带密码orderdata）
                            OrderData = LittleUtils.GetNumString(OrderData);
                            if (OrderData.isEmpty()) {
                                Log.e(TAG, "额外数据为空");
                                RestData();
                            } else {
                                LooKRoom();
                            }
                            break;
                        case 3:// 暂停刷房
                            OrderNum = -1;
                            reset = false;
                            IsClicked = false;
                            break;
                        case 4: //解锁房间
                            UnLock();
                            break;
                        case 5: //清公屏 （执行关公屏，再执行开公屏）
                            ClearGping();
                            break;
                        case 6: //打开公屏
                            OpenGping();
                            break;
                        case 7: //关闭公屏
                            CloseGping();
                            break;
                        case 8: //禁麦操作（Orderdata表示几号位的麦克风）
                            ClickNum = LittleUtils.GetNumString(OrderData);
                            if (OrderData.isEmpty()) {
                                Log.e(TAG, "额外数据为空");
                                RestData();
                            } else {
                                BanTalk();
                            }
                            break;
                        case 9: //解除禁麦（orderdata表示几号位的麦克风）
                            ClickNum = LittleUtils.GetNumString(OrderData);
                            if (OrderData.isEmpty()) {
                                Log.e(TAG, "额外数据为空");
                                RestData();
                            } else {
                                unBanTalk();
                            }
                            break;
                        case 10: //踢出房间 (orderdata表示几号位的人)
                            ClickNum = LittleUtils.GetNumString(OrderData);
                            if (OrderData.isEmpty()) {
                                Log.e(TAG, "额外数据为空");
                                RestData();
                            } else {
                                Tpeople();
                            }
                            break;
                        case 11: // 抱orderdata号位置下麦
                            ClickNum = LittleUtils.GetNumString(OrderData);
                            if (OrderData.isEmpty()) {
                                Log.e(TAG, "额外数据为空");
                                RestData();
                            } else {
                                Baonum();
                            }
                            break;
                        case 12: //抱树 把ID为m的人抱上n号麦
                            ClickNum = LittleUtils.GetNumString(OrderData.substring(0, 1));
                            InputData = LittleUtils.GetNumString(OrderData.substring(1));
                            if (OrderData.isEmpty() || ClickNum.isEmpty() || InputData.isEmpty()) {
                                Log.e(TAG, "额外数据为空");
                                RestData();
                            } else {
                                BaoShu();
                            }
                            break;
                        case 13: //封闭orderdata位置的座位
                            ClickNum = LittleUtils.GetNumString(OrderData);
                            if (OrderData.isEmpty()) {
                                Log.e(TAG, "额外数据为空");
                                RestData();
                            } else {
                                Feng();
                            }
                            break;
                        case 14://解除orderdata的封闭座位
                            ClickNum = LittleUtils.GetNumString(OrderData);
                            if (OrderData.isEmpty()) {
                                Log.e(TAG, "额外数据为空");
                                RestData();
                            } else {
                                Unfeng();
                            }
                            break;
                        case 15: //换喇叭 +orderdata数据
                            if (OrderData.isEmpty()) {
                                Log.e(TAG, "额外数据为空");
                                RestData();
                            } else {
                                EditLaba();
                            }
                            break;
                        case 16: //抱id为n的人上m号麦，然后踢出房间
                            ClickNum = LittleUtils.GetNumString(OrderData.substring(0, 1));
                            InputData = LittleUtils.GetNumString(OrderData.substring(1));
                            if (OrderData.isEmpty() || ClickNum.isEmpty() || InputData.isEmpty()) {
                                Log.e(TAG, "额外数据为空");
                                RestData();
                            } else {
                                BaoTi();
                            }
                            break;
                        case 17: //调整速度
                            String speed = LittleUtils.GetNumString(OrderData);
                            if (!speed.isEmpty()) {
                                switch (Integer.valueOf(speed)) {
                                    case 1:
                                        timedelay = 200l;
                                        SPUtils.put(getApplicationContext(), "speed", "1");
                                        break;
                                    case 2:
                                        timedelay = 400l;
                                        SPUtils.put(getApplicationContext(), "speed", "2");
                                        break;
                                    case 3:
                                        timedelay = 600l;
                                        SPUtils.put(getApplicationContext(), "speed", "3");
                                        break;
                                }
                            }
                            TimeSleep = timedelay;
                            reset = false;
                            OrderNum = 0;
                            IsClicked = false;
                            break;
                    }
                    try {
                        sleep(TimeSleep);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 循环进行刷房
     */
    public void LoopMain() {
        if (reset) {
            AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
            if (saveWindows.equals(page1) && !lastWindows.equals(Progressdialg)) {
                MainPage2MyRoom(nodeInfo);
            } else if (saveWindows.equals(page_room) && !lastWindows.equals(page_room_exit_menu_exitdialog)) {
                ClickRightBtn(nodeInfo);
            } else if (saveWindows.equals(page_room_exit_menu)) {
                if (!ClickPopExitButton(nodeInfo, ExitRoom)) {
                    performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
                }
            } else if (saveWindows.equals(page_room_exit_menu_exitdialog)) {
                if (!ClickIdBtn(ExitDialgoRightBtn, nodeInfo)) {
                    performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
                }
            }
        } else {
            reSetWindows();
        }
    }

    /**
     * 主页跳转我的房间
     *
     * @param nodeInfo
     */
    public void MainPage2MyRoom(final AccessibilityNodeInfo nodeInfo) {
        try {
            List<AccessibilityNodeInfo> list2 = nodeInfo.findAccessibilityNodeInfosByText("进入我的房间");
            for (AccessibilityNodeInfo nodeInfo1 : list2) {

                if (nodeInfo1.getText().toString().equals(EnterRoom) && nodeInfo1.getParent().getClassName().equals(LinLayout) && nodeInfo1.getParent().isClickable()) {
                    if (nodeInfo1 != null && nodeInfo1.getParent() != null && nodeInfo1.getParent().getParent() != null && nodeInfo1.getParent().getParent().getParent() != null) {
                        //判断是首页并且点击房间标签;
                        Log.e(TAG, "点击进入我的房间");
                        nodeInfo1.getParent().performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    }
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "点击进入我的房间出现错误:" + e);
        }
    }

    /**
     * 点击右上角退出按钮弹出框
     *
     * @param nodeInfo
     */
    private void ClickRightBtn(AccessibilityNodeInfo nodeInfo) {
        try {
            List<AccessibilityNodeInfo> list = nodeInfo.findAccessibilityNodeInfosByViewId(ExitBtnId);
            if (list.size() != 0) {
                list.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
            }
        } catch (Exception e) {
            Log.e(TAG, "err" + e);
            return;
        }


    }

    /**
     * 退出弹出的POP框点击按钮列表
     *
     * @param nodeInfo
     * @param buttonname
     */
    private boolean ClickPopExitButton(AccessibilityNodeInfo nodeInfo, String buttonname) {
        List<AccessibilityNodeInfo> list2 = null;
        try {
            list2 = nodeInfo.findAccessibilityNodeInfosByText(buttonname);
        } catch (Exception e) {
            Log.e(TAG, "错误信息:未找到按钮:" + e);
            return false;
        }
        if (!list2.isEmpty()) {
            for (AccessibilityNodeInfo nodeInfo1 : list2) {
                if (nodeInfo1 != null && nodeInfo1.getParent() != null) {
                    if (nodeInfo1.getText().toString().equals(buttonname) && nodeInfo1.getClassName().equals(TextViewName) && nodeInfo1.getParent().getClassName().equals(LinLayout)) {
                        nodeInfo1.getParent().performAction(AccessibilityNodeInfo.ACTION_CLICK);
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 点击按钮(通过ID查找的)
     */
    public boolean ClickIdBtn(String BtnID, AccessibilityNodeInfo nodeInfo) {
        List<AccessibilityNodeInfo> list = null;
        try {
            list = nodeInfo.findAccessibilityNodeInfosByViewId(BtnID);
        } catch (Exception e) {
            Log.e(TAG, "点击右键失败" + e);
            return false;
        }
        if (list == null || list.isEmpty()) {
            Log.e(TAG, "点击右键失败:未找到节点");
            return false;
        }
        AccessibilityNodeInfo nodeInfo1 = list.get(0);
        nodeInfo1.performAction(AccessibilityNodeInfo.ACTION_CLICK);
        return true;
    }

    /**
     * 恢复到我的房间内
     */
    private void reSetWindows() {
        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
        if (saveWindows.equals(page_room) && !lastWindows.equals(page_room_exit_menu_exitdialog)) {
            reset = true;
            Log.e(TAG, "回到聊天室");
        } else if (saveWindows.equals(page1) && !lastWindows.equals(Progressdialg)) {
            //如果在首页
            MainPage2MyRoom(nodeInfo);
        } else if (saveWindows.equals(page_room_exit_menu_exitdialog)) {
            ClickIdBtn(ExitDialgoleftBtn, nodeInfo);
        } else if (!saveWindows.equals(Progressdialg)) {
            performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);//返回                                       物理按键
        }
    }


    /**
     * 修改房间名
     */
    private void ReNameRoom() {
        if (reset) {
            AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
            if (saveWindows.equals(page_room)) {
                ClickRightBtn(nodeInfo);
            } else if (saveWindows.equals(page_room_exit_menu)) {
                ClickPopExitButton(nodeInfo, NotifyRoomName);
            } else if (saveWindows.equals(page_rename_room)) {
                reNameRoomName(nodeInfo, OrderData);
            }
        } else {
            reSetWindows();
        }
//        nodeInfo.recycle();
//        checkMode(saveState);
    }

    /**
     * 修改房间名操作操作
     *
     * @param nodeInfo
     */
    private void reNameRoomName(final AccessibilityNodeInfo nodeInfo, final String Rename_name) {
        List<AccessibilityNodeInfo> list = null;
        try {
            list = nodeInfo.findAccessibilityNodeInfosByViewId(Edittext_rename);
        } catch (Exception e) {
            return;
        }
        if (list == null) {
            return;
        }
        final java.util.List<AccessibilityNodeInfo> finalList = list;
        new Handler(mContext.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                AccessibilityNodeInfo nodeInfo1 = finalList.get(0);
                Bundle arguments = new Bundle();
                arguments.putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT,
                        AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE);
                arguments.putBoolean(AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN,
                        true);
                nodeInfo1.performAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY,
                        arguments);
                ClipData clip = ClipData.newPlainText("111", Rename_name);
                clipboardManager.setPrimaryClip(clip);
                if (!clipboardManager.getPrimaryClip().getItemAt(0).getText().toString().equals(Rename_name)) {
                    nodeInfo1.performAction(AccessibilityNodeInfo.ACTION_PASTE);
                }
                nodeInfo1.performAction(AccessibilityNodeInfo.ACTION_PASTE);
                ClickIdBtn(Btn_PostRename, nodeInfo);//修改失败会直接退出
                RestData();
            }
        });


    }

    /**
     * 锁房
     */
    private void LooKRoom() {
        if (reset) {
            AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
            if (saveWindows.equals(page_room)) {
                ClickRightBtn(nodeInfo);
            } else if (saveWindows.equals(page_room_exit_menu)) {
                if (!ClickPopExitButton(nodeInfo, LookRoom)) {
                    ClickPopExitButton(nodeInfo, unLookRoom);
                }
            } else if (saveWindows.equals(page_lock_room)) {
                LockPass(nodeInfo);
            } else if (saveWindows.equals(page_room_exit_menu_exitdialog)) {
                ClickIdBtn(ExitDialgoRightBtn, nodeInfo);
            }
        } else {
            reSetWindows();
        }

    }

    /**
     * 锁房加密操作
     *
     * @param nodeInfo
     */
    private void LockPass(final AccessibilityNodeInfo nodeInfo) {
        List<AccessibilityNodeInfo> list = null;
        try {
            list = nodeInfo.findAccessibilityNodeInfosByViewId(edit_RoomPass);
        } catch (Exception e) {
            return;
        }
        if (list == null) {
            return;
        }
        final java.util.List<AccessibilityNodeInfo> finalList = list;
        new Handler(mContext.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                AccessibilityNodeInfo nodeInfo1 = finalList.get(0);
                Bundle arguments = new Bundle();
                arguments.putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT,
                        AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE);
                arguments.putBoolean(AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN,
                        true);
                nodeInfo1.performAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY,
                        arguments);
                ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clip = ClipData.newPlainText("321", OrderData);
                clipboard.setPrimaryClip(clip);
                nodeInfo1.performAction(AccessibilityNodeInfo.ACTION_PASTE);

                ClickIdBtn(Btn_LoockRoom, nodeInfo);//修改失败会直接退出进入循环
                RestData();
            }
        });

    }


    /**
     * 解锁房间
     */
    private void UnLock() {
        if (reset) {
            AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
            if (saveWindows.equals(page_room)) {
                ClickRightBtn(nodeInfo);
            } else if (saveWindows.equals(page_room_exit_menu)) {
                if (!ClickPopExitButton(nodeInfo, unLookRoom)) {
                    //解锁失败
                    if (!IsClicked) {
                        Log.e(TAG, "解锁房间失败");
                        RestData();
                        IsClicked = true; //防止点击过快，导致重复点击解锁失败
                    }
                } else {
                    if (!IsClicked) {
                        Log.e(TAG, "解锁房间成功");
                        IsClicked = true;
                    }
                }

            } else if (saveWindows.equals(page_room_exit_menu_exitdialog)) {
//                List<AccessibilityNodeInfo> list2 = nodeInfo.findAccessibilityNodeInfosByViewId(ExitDialgoRightBtn);
//                list2.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
                ClickIdBtn(ExitDialgoRightBtn, nodeInfo);
                RestData();
            }
        } else {
            reSetWindows();
        }
    }

    /**
     * 先开后关 (清公屏)
     */
    private void ClearGping() {
        if (reset) {
            AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
            if (saveWindows.equals(page_room)) {
                ClickRightBtn(nodeInfo);
            } else if (saveWindows.equals(page_room_exit_menu)) {
                if (!ClickPopExitButton(nodeInfo, CloseChat)) {
                    ClickPopExitButton(nodeInfo, OpenChat);
                    RestData();
                }
            }
        } else {
            reSetWindows();
        }
    }

    /**
     * 开公屏
     */
    private void OpenGping() {
        if (reset) {
            AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
            if (saveWindows.equals(page_room)) {
                ClickRightBtn(nodeInfo);
            } else if (saveWindows.equals(page_room_exit_menu)) {
                ClickPopExitButton(nodeInfo, OpenChat);
                RestData();
            }
        } else {
            reSetWindows();
        }
    }

    /**
     * 关公屏
     */

    private void CloseGping() {
        if (reset) {
            AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
            if (saveWindows.equals(page_room)) {
                ClickRightBtn(nodeInfo);
            } else if (saveWindows.equals(page_room_exit_menu)) {
                ClickPopExitButton(nodeInfo, CloseChat);
                RestData();
            }
        } else {
            reSetWindows();
        }
    }

    /**
     * 点击num顺序的人
     *
     * @param num
     */
    private boolean ClickNum(int num, AccessibilityNodeInfo nodeInfo) {
        try {
            List<AccessibilityNodeInfo> list = nodeInfo.findAccessibilityNodeInfosByViewId(Grid_chatroom);
            if (!list.isEmpty() && num <= 8 && num >= 1) {
                Log.e(TAG, "点击了：" + num);
                final AccessibilityNodeInfo nodeInfo1 = list.get(0).getChild(num - 1);
                Log.e(TAG, "延迟点击");
                new Handler(mContext.getMainLooper()
                ).postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (nodeInfo1 != null) {
                            nodeInfo1.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                        }
                    }
                }, 100);
                return true;
            }
        } catch (Exception e) {
            Log.e(TAG, "异常，未发现按钮:" + e);
            return true;
        }
        return false;
    }


    /**
     * 静麦
     */
    private void BanTalk() {
        if (reset) {
            AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
            if (saveWindows.equals(page_room)) {
                if (!IsClicked) {
                    if (!ClickNum(Integer.parseInt(ClickNum), nodeInfo)) {
                        performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
                    }
                    IsClicked = true;
                }
            } else if (saveWindows.equals(page_room_exit_menu)) {
                if (!IsClicked) {
                    if (ClickPopExitButton(nodeInfo, BanTalk)) {
                        RestData(); //禁麦成功
                    } else {
                        performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
                        RestData();
                    }
                    IsClicked = true;
                }
            }
        } else {
            reSetWindows();
        }
    }


    /**
     * 解除静麦
     */
    private void unBanTalk() {
        if (reset) {
            AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
            if (saveWindows.equals(page_room)) {
                if (!IsClicked) {
                    if (!ClickNum(Integer.parseInt(ClickNum), nodeInfo)) {
                        performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
                        RestData();
                    }
                    IsClicked = true;
                }
            } else if (saveWindows.equals(page_room_exit_menu)) {
                if (!IsClicked) {
                    if (ClickPopExitButton(nodeInfo, unBanTalk)) {
                        RestData();
                    } else {
                        performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
                        RestData();
                    }
                    IsClicked = true;
                }
            }
        } else {
            reSetWindows();
        }
    }

    /**
     * T人
     */
    private void Tpeople() {
        if (reset) {
            AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
            if (saveWindows.equals(page_room)) {
                if (!IsClicked) {
                    if (!ClickNum(Integer.parseInt(ClickNum), nodeInfo)) {
                        performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
                        RestData();
                    }
                    IsClicked = true;
                }

            } else if (saveWindows.equals(page_room_exit_menu)) {
                if (!IsClicked) {
                    if (!ClickPopExitButton(nodeInfo, Tman)) {
                        //T人失败，这个位置没有人
                        performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
                        RestData();
                    }
                    IsClicked = true;
                }
            } else if (saveWindows.equals(page_room_exit_menu_exitdialog)) {
                ClickIdBtn(ExitDialgoRightBtn, nodeInfo);
                RestData();
            }
        } else {
            reSetWindows();
        }

    }

    /**
     * 抱人下麦
     */
    private void Baonum() {
        if (reset) {
            AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
            if (saveWindows.equals(page_room)) {
                if (!IsClicked) {
                    if (!ClickNum(Integer.parseInt(ClickNum), nodeInfo)) {
                        RestData();
                    }
                    IsClicked = true;
                }
            } else if (saveWindows.equals(page_room_exit_menu)) {
                if (!IsClicked) {
                    if (!ClickPopExitButton(nodeInfo, BaoMan)) {
                        //T人失败，这个位置没有人
                        performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
                        RestData();
                    }
                    IsClicked = true;
                }
            }
        } else {
            reSetWindows();
        }

    }


    /**
     * 抱树上麦
     */
    private void BaoShu() {
        if (reset) {
            AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
            if (saveWindows.equals(page_room)) {
                if (!ClickNum(Integer.parseInt(ClickNum), nodeInfo)) {
                    RestData();
                }
            } else if (saveWindows.equals(page_room_exit_menu)) {
                if (!IsClicked) {
                    if (!ClickPopExitButton(nodeInfo, Baoshu)) {
                        if (!ClickPopExitButton(nodeInfo, ShangMai)) {
                            performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
                        }
                    }
                    IsClicked = true;
                }
            } else if (saveWindows.equals(Baosheishangmai)) {
                ClickIdBtn(Btn_SearchUser, nodeInfo);
            } else if (saveWindows.equals(page_room_serach_dialog)) {
                WriteId(nodeInfo);
                RestData();
            }
        } else {
            reSetWindows();
        }
    }

    /**
     * 提交抱树ID
     *
     * @param nodeInfo
     */
    private void WriteId(final AccessibilityNodeInfo nodeInfo) {
        List<AccessibilityNodeInfo> list = null;
        try {
            list = nodeInfo.findAccessibilityNodeInfosByViewId(Edit_SearchUser);
        } catch (Exception e) {
            return;
        }
        if (list == null || list.isEmpty()) {
            return;
        }
        final AccessibilityNodeInfo nodeInfo1 = list.get(0);
        new Handler(mContext.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                Bundle arguments = new Bundle();
                nodeInfo1.performAction(AccessibilityNodeInfo.ACTION_FOCUS);
                arguments.putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT,
                        AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE);
                arguments.putBoolean(AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN,
                        true);
                nodeInfo1.performAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY,
                        arguments);
                ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clip = ClipData.newPlainText("636", InputData);
                clipboard.setPrimaryClip(clip);
                nodeInfo1.performAction(AccessibilityNodeInfo.ACTION_PASTE);
                ClickIdBtn(Btn_BaoUser, nodeInfo);//修改失败会直接退出
            }
        });

    }

    /**
     * 封闭座位
     */
    private void Feng() {
        if (reset) {
            AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
            if (saveWindows.equals(page_room)) {
                if (!IsClicked) {
                    if (!ClickNum(Integer.parseInt(ClickNum), nodeInfo)) {
                        RestData();
                    }
                    IsClicked = true;
                }

            } else if (saveWindows.equals(page_room_exit_menu)) {
                if (!IsClicked) {
                    if (ClickPopExitButton(nodeInfo, Baoshu)) {
                        RestData();
                    } else {
                        //禁麦失败，这个位置没有人 或者这个麦已经被禁了
                        performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
                        RestData();
                    }
                    IsClicked = true;
                }

            }
        } else {
            reSetWindows();
        }
    }


    /**
     * 解除封闭座位
     */
    private void Unfeng() {
        if (reset) {
            AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
            if (saveWindows.equals(page_room)) {
                if (!IsClicked) {
                    if (!ClickNum(Integer.parseInt(ClickNum), nodeInfo)) {
                        RestData();
                    }
                    IsClicked = true;
                }
            } else if (saveWindows.equals(page_room_exit_menu)) {
                if (!IsClicked) {
                    if (ClickPopExitButton(nodeInfo, Jiefeng)) {
                        RestData();
                    } else {
                        performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
                        RestData();
                    }
                    IsClicked = true;
                }
            }
        } else {
            reSetWindows();
        }
    }

    /**
     * 替换喇叭内容
     */
    private void EditLaba() {
        if (reset) {
            final AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
            if (saveWindows.equals(page_room)) {
                if (!IsClicked) {
                    if (ClickIdBtn(btn_edit_laba, nodeInfo)) {
                        WirteLa(nodeInfo);
                    }
                    IsClicked = true;
                }
            }
        } else {
            reSetWindows();
        }
    }

    /**
     * 修改喇叭
     *
     * @param nodeInfo
     */
    private void WirteLa(final AccessibilityNodeInfo nodeInfo) {
        List<AccessibilityNodeInfo> list = null;
        try {
            list = nodeInfo.findAccessibilityNodeInfosByViewId(edit_laba);
        } catch (Exception e) {
            return;
        }
        if (list == null || list.isEmpty()) {
            return;
        }
        Log.e(TAG, "输入的值:" + OrderData);
        final java.util.List<AccessibilityNodeInfo> finalList = list;
        new Handler(mContext.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                final AccessibilityNodeInfo nodeInfo1 = finalList.get(0);
                nodeInfo1.performAction(AccessibilityNodeInfo.ACTION_FOCUS);
                final ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                nodeInfo1.performAction(AccessibilityNodeInfo.ACTION_SELECT);
                Log.e(TAG, "选中的开始:" + nodeInfo1.getTextSelectionStart());
                Log.e(TAG, "选中的结束:" + nodeInfo1.getTextSelectionEnd());
                int max = nodeInfo1.getText().toString().length();
                Log.e(TAG, "文本最大长度" + max);
                Bundle arg = new Bundle();
                ClipData clip = ClipData.newPlainText("000", OrderData);
                clipboard.setPrimaryClip(clip);
                arg.putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, 0);
                arg.putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, max);
                nodeInfo1.performAction(AccessibilityNodeInfo.ACTION_SET_SELECTION, arg);
                nodeInfo1.performAction(AccessibilityNodeInfo.ACTION_PASTE);
                ClickIdBtn(Btn_saveLaba, nodeInfo);
                RestData();
            }
        });
    }


    /**
     * 抱踢上麦
     */
    private void BaoTi() {
        if (reset) {
            AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
            if (saveWindows.equals(page_room)) {
                if (!IsClicked) {
                    if (!ClickNum(Integer.parseInt(ClickNum), nodeInfo)) {
                        RestData();
                    }
                    IsClicked = true;
                }
            } else if (saveWindows.equals(page_room_exit_menu)) {
                if (!IsClicked) {
                    if (!ClickPopExitButton(nodeInfo, Baoshu)) {
                        if (!ClickPopExitButton(nodeInfo, ShangMai)) {
                            performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
                        }
                    }
                    IsClicked = true;
                }
            } else if (saveWindows.equals(Baosheishangmai)) {
                ClickIdBtn(Btn_SearchUser, nodeInfo);
            } else if (saveWindows.equals(page_room_serach_dialog)) {
                WriteId(nodeInfo);
                OrderNum = 10;
                OrderData = ClickNum;
                reset = false;
            }
        } else {
            reSetWindows();
        }
    }


    /**
     * 是否开启容错线程
     */
    private boolean StartErrorTheard = false;

    /**
     * 容错线程内的class存储对象
     */
    private String errorClass = null;

    /**
     * 容错线程内的存储出错页面次数的变量
     */
    private int savesecond = 0;

    /**
     * 容错线程
     */
    private Thread errorthread = new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {
                time = (int) (1L * TimeSleep / 200l) + 10;
                if (StartErrorTheard && CommonValue.CanUse) {
                    if (errorClass == null) {
                        errorClass = saveWindows;
                    } else {
                        if (errorClass.equals(saveWindows)) {
                            savesecond++;
                            if (savesecond == (time + 1)) {
                                //reset 重置命令
                                Log.e(TAG, "检测到错误，恢复初始状态");
                                savesecond = 0;
                                RestData();
                            }
                        } else {
                            savesecond = 0;
                            errorClass = saveWindows;
                        }
                    }
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    });


    private Thread CheckThread = new Thread(new Runnable() {
        @Override
        public void run() {
            TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
            final String szImei = TelephonyMgr.getDeviceId();
            while (startcheck) {
                Log.e(TAG, "开始LX");
                new Handler(mContext.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        Check(szImei);
                    }
                });
                try {
                    Thread.sleep(60000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    });

    public void Check(String tzcode) {
        RequestParams requestParams = new RequestParams();
        if (CommonValue.uid.equals("-1")) {
            CommonValue.CanUse = false;
            handler.sendEmptyMessage(2);
            return;
        }
        requestParams.add("userid", CommonValue.uid);
        requestParams.add("signature", MD5.md5(tzcode));
        new AsynHttp().sendPost(URLString.TIMECHECK, requestParams, new NetCallBack() {
            @Override
            public void Success(String arg) {
                Log.e(TAG, arg);
                LoginBean bean = new Gson().fromJson(arg, LoginBean.class);
                if (bean.getCode() == 200) {
                    CommonValue.CanUse = true;
                    CommonValue.CanRun = true;
                    Log.e(TAG, "服务器验证成功");
                } else {
                    //轮训失败
                    CommonValue.CanUse = false;
                    CommonValue.CanRun = false;
                    handler.sendEmptyMessage(2);
                    Log.e(TAG, "服务器验证失败");
                }
            }

            @Override
            public void Failure(Throwable arg) {
                //轮训失败 ，服务器关闭或者无网络
                CommonValue.CanUse = false;
                CommonValue.CanRun = false;
                handler.sendEmptyMessage(3);
                Log.e(TAG, "服务器验证失败2");
            }
        });
    }

    private void GetPwd() {
        String pwd = (String) SPUtils.get(getApplication(), "password", "333");
        if (pwd != null) {
            RecivePwd = pwd;
        }
    }

    private long timedelay = 200l;

    public void GetSpeed() {
        String sped = (String) SPUtils.get(getApplicationContext(), "speed", "2");
        switch (Integer.valueOf(sped)) {
            case 1:
                timedelay = 200l;
                break;
            case 2:
                timedelay = 400l;
                break;
            case 3:
                timedelay = 600l;
                break;
        }
    }
}
